﻿namespace ApiServer.Utilitys.FileMiddleware
{
    /// <summary>
    ///图片下载中间件，客户端通过URL访问图片，中间件读取图片并返回给客户端
    /// 如果中间件匹配到URL请求，直接读取图片文件并返回给客户端，否则继续往下执行中间件链
    /// </summary>
    public class DownloadImagesMiddleware
    {
        private readonly RequestDelegate _next;
        private string? _directoryPath = null;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="next"></param>
        /// <param name="directoryPath"></param>
        public DownloadImagesMiddleware(RequestDelegate next, string directoryPath)
        {
            _next = next;
            _directoryPath = directoryPath;
        }

        /// <summary>
        /// 读取图片信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            //Console.WriteLine("This is DownloadFilesMiddleware in");
            //await this._next.Invoke(httpContext);//正常流程
            //Console.WriteLine("This is DownloadFilesMiddleware out");

            if (
                context.Request.Path.Value!.EndsWith(".jpg")
                || context.Request.Path.Value!.EndsWith(".png")
            ) //规则支持自定义
            {
                string fileUrl = $"{_directoryPath}{context.Request.Path.Value}";
                if (!File.Exists(fileUrl)) //如果文件不存在就继续往后的流程
                {
                    fileUrl = $"{_directoryPath}/FileUpload/NoImg.jpg";
                }
                #region MyRegion
                {
                    context.Request.EnableBuffering();
                    context.Request.Body.Position = 0;
                    var responseStream = context.Response.Body;
                    using (FileStream newStream = new FileStream(fileUrl, FileMode.Open))
                    {
                        context.Response.Body = newStream;
                        newStream.Position = 0;
                        var responseReader = new StreamReader(newStream);
                        var responseContent = await responseReader.ReadToEndAsync();
                        newStream.Position = 0;
                        await newStream.CopyToAsync(responseStream);
                        context.Response.Body = responseStream;
                    }
                }
                #endregion
            }
            else
            {
                await _next(context); //中间件链式调用下一个中间件
            }
        }
    }
}
